<?php

class Buzz_CommentParser {
    private $gmapper;
    private $emapper;
    private $url;

    public function __construct() {
        $this->gmapper = new Application_Model_GroupMapper();
        $this->emapper = new Application_Model_ElementMapper();
        $this->url = new Zend_View_Helper_Url();
    }

    public function parse($comment) {
        $groupTags = $this->findGroups($comment);
        $elemTags = $this->findElements($comment);

        $replacements = array();
        $replacement[0] = array();
        $replacement[1] = array();
        $groups = array();
        $elems = array();

        foreach ($groupTags as $tag) {
            $group = $this->gmapper->find(substr($tag, 2));
            if ($group != null) {
                $replacement[0][] = '/' . $tag . '/';
                $replacement[1][] = $this->makeGroupReplacement($group);
                $groups[] = $group;
            }
        }

        foreach ($elemTags as $tag) {
            $elem = $this->emapper->find(substr($tag, 2));
            if ($elem != null) {
                $replacement[0][] = '/' . $tag . '/';
                $replacement[1][] = $this->makeElemReplacement($elem);
                $elems[] = $elem;
            }
        }
        $rewritten = preg_replace($replacement[0], $replacement[1], $comment);
        return array("groups"   => $groups, 
                    "elements"  => $elems, 
                    "rewritten" => $rewritten);
    }

    private function makeGroupReplacement(Application_Model_Group $group) {
        $url = $this->url->url(array("id" => $group->id()), "groupview", true);
        return "<a href=\"$url\">" . $group->name() . "</a>";
    }

    private function makeElemReplacement(Application_Model_Element $element) {
        $url = $this->url->url(array("id" => $element->id()), "viewelement", true);
        return "<a href=\"$url\">" . $element->name() . "</a>";
    }

    private function findGroups($comment) {
        $matches = array();
        preg_match_all('/#g\d+/', $comment, $matches);
        return $matches[0];
    }

    private function findElements($comment) {
        $matches = array();
        preg_match_all('/#e\d+/', $comment, $matches);
        return $matches[0];
    }
}
